<template>
  <a-card
    class="menu-content-preview-code"
    :bodyStyle="{ flex: 1, overflowY: 'auto', position: 'relative' }"
    :bordered="false"
    title="内容预览"
  >
    <a-spin
      v-if="loading"
      :spinning="loading"
      style="
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10;
        background: rgba(255, 255, 255, 0.5);
      "
    />
    <preview-code v-else :content="content" />
  </a-card>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import PreviewCode from '@/components/preview-code.vue'
import { getFilePreview } from '@/api/db.js'
import { useDbType } from '@/views/db-management/provide-context.js'
import { message as Message } from 'ant-design-vue'
/**
 * 外部参数
 */
let props = defineProps({
  data: {
    required: true,
  },
})
let dbType = useDbType()
let loading = ref(false)
let content = ref()
onMounted(() => {
  loading.value = true
  getFilePreview({ id: props?.data?.id }, dbType)
    .then(response => {
      let reader = new FileReader()
      // 读取文件中的内容，执行读文件函数，设置编码格式。
      reader.readAsText(response.data, 'UTF-8')
      // 读取文件，得到文件内容。
      reader.onload = function (e) {
        content.value = e.target.result
        loading.value = false
      }
      reader.onerror = function (e) {
        Message.error('文件读取失败')
      }
    })
    .catch(async e => {
      try {
        let text = await e.text()
        let json = JSON.parse(text)
        Message.error(json.errorMessage || json.message || '文件加载失败')
      } catch (err) {
        Message.error('文件加载失败')
      }
      loading.value = false
    })

  // axios
  //   .get('/test-file/index.html', { responseType: 'blob' })
  //   .then(response => {
  //     let reader = new FileReader()
  //     // 读取文件中的内容，执行读文件函数，设置编码格式。
  //     reader.readAsText(response.data, 'UTF-8')
  //     // 读取文件，得到文件内容。
  //     reader.onload = function (e) {
  //       content.value = e.target.result
  //       loading.value = false
  //     }
  //   })
})
</script>
<style scoped lang="less">
.menu-content-preview-code {
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
</style>
